package com.example.safeassistan.my.fragment;

import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.example.safeassistan.R;
import com.example.safeassistan.base.BaseModel;
import com.example.safeassistan.base.BaseVPFragment;
import com.example.safeassistan.constants.UrlConstants;
import com.example.safeassistan.http.HttpRequest;
import com.example.safeassistan.http.HttpStringCallBack;
import com.example.safeassistan.my.activity.ActivityfeedBackDetail;
import com.example.safeassistan.my.adapter.FeedBackListAdapter;
import com.example.safeassistan.my.model.FeedBackListModel;
import com.example.safeassistan.train.activity.ActivityKnowledgeBaseDetail;
import com.example.safeassistan.train.adapter.KonwLedgeBaseAdapter;
import com.example.safeassistan.train.model.MateralList;
import com.example.safeassistan.utile.JsonUtils;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;


public class FeedBackFragment extends BaseVPFragment implements View.OnClickListener{
    private FeedBackListAdapter materialAdapter;
    private RecyclerView rcView;
    private LinearLayout llNodata;
    private View view;
    private Context context;
    private List<FeedBackListModel.ResultDTO.RecordsDTO> data;

    private int type=0;//0未处理 1已处理
    private int currentPage=1;
    private int pageSize=10;
    private SmartRefreshLayout refresh;
    private int count=0;

    public static FeedBackFragment newInstance(int type) {
        Bundle arguments = new Bundle();
        arguments.putInt("type",type);
        FeedBackFragment fl = new FeedBackFragment();
        fl.setArguments(arguments);
        return fl;
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        if (view == null) {
            view = inflater.inflate(R.layout.fragment_message, container, false);
            context = getActivity();
            initView();
        }
        return view;
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        initView();
    }

    @Override
    protected void onFragmentVisibleChange(boolean isVisible) {

    }

    @Override
    protected void onFragmentFirstVisible() {
            getData();
    }

    //获取数据
    public void getData(){
        JSONObject map = new JSONObject();
        try {
            map.put("result",String.valueOf(type));
            map.put("pageNo", String.valueOf(currentPage));
            map.put("pageSize",String.valueOf(pageSize));
        } catch (JSONException e) {
            e.printStackTrace();
        }

        new HttpRequest(context).doPost(UrlConstants.userInfoqueryFeedbackList, "", map, new HttpStringCallBack() {
            @RequiresApi(api = Build.VERSION_CODES.M)
            @Override
            public void onSuccess(Object result) {
                String datas = result.toString();
                JSONObject jsonObject = null;
                try {
                    jsonObject = new JSONObject(datas);
                    String message = jsonObject.getString("message");
                    Boolean success = jsonObject.getBoolean("success");
                    if (success) {
                        Object obj = JsonUtils.fromJson(result.toString(), FeedBackListModel.class);
                        if (obj instanceof FeedBackListModel) {
                            FeedBackListModel model=(FeedBackListModel)obj;
                            if (currentPage == 1) {
                                data.clear();
                                count = model.getResult().getTotal();
                                if (model.getResult().getRecords().size() > 0) {
                                    llNodata.setVisibility(View.GONE);
                                    rcView.setVisibility(View.VISIBLE);
                                    data=model.getResult().getRecords();
                                    materialAdapter=new FeedBackListAdapter(data);
                                    rcView.setLayoutManager(new LinearLayoutManager(context));
                                    rcView.setAdapter(materialAdapter);
                                    if (materialAdapter.getItemCount() < count) {
                                        //还有多的数据
                                        refresh.finishRefresh();
                                    } else {
                                        //没有更多数据（上拉加载功能将显示没有更多数据）
                                        refresh.finishRefreshWithNoMoreData();
                                    }
                                    materialAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
                                        @Override
                                        public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                                            ActivityfeedBackDetail.actionStart(context,data.get(position).getId(),type);
                                        }
                                    });
                                } else {
                                    rcView.setVisibility(View.GONE);
                                    refresh.finishRefreshWithNoMoreData();
                                    llNodata.setVisibility(View.VISIBLE);
                                }
                            } else {
                                data.addAll(model.getResult().getRecords());
                                materialAdapter.notifyDataSetChanged();
                                if (materialAdapter.getItemCount() < count) {
                                    //还有多的数据
                                    refresh.finishLoadMore();
                                } else {
                                    //没有更多数据（上拉加载功能将显示没有更多数据）
                                    refresh.finishLoadMoreWithNoMoreData();//将不会再次触发加载更多事件
                                }
                            }
                        }
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(int code, String msg) {
                Toast.makeText(context,msg,Toast.LENGTH_SHORT).show();
            }
        });
    }

    public void initView(){
        type=getArguments().getInt("type");
        refresh=view.findViewById(R.id.refresh);
        rcView=view.findViewById(R.id.rcView);
        llNodata=view.findViewById(R.id.llNodata);
        setView();
    }

    public void setView(){
        data=new ArrayList<>();
        refresh.setEnableAutoLoadMore(true);//开启自动加载功能（非必须）
        refresh.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(final RefreshLayout refreshLayout) {
                refreshLayout.getLayout().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        currentPage = 1;
                        getData();
                    }
                }, 1000);
            }
        });
        refresh.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull final RefreshLayout refreshLayout) {
                refreshLayout.getLayout().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        currentPage++;
                        getData();
                    }
                }, 1000);
            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            default:
                break;
        }
    }
}